import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import {
  getBanners,
  getHotRecommend,
  getNewAlbum,
  getPlayListDetail
} from '@/views/discover/c-views/recommend/service'

export const fetchRecommendDataAction = createAsyncThunk(
  'fetchdata',
  (_, { dispatch }) => {
    //获取轮播图数据
    getBanners().then((res) => {
      dispatch(changeBannerAction(res.banners))
    })
    getHotRecommend(8).then((res) => {
      dispatch(changeHotRecommendAction(res.result))
    })
    getNewAlbum().then((res) => {
      dispatch(changeNewAlbumActions(res.albums))
    })
  }
)

const rankingIds = [19723756, 3779629, 2884035]
export const fetchRankingDataAction = createAsyncThunk(
  'rankingData',
  (_, { dispatch }) => {
    const promises: Promise<any>[] = []

    for (const id of rankingIds) {
      promises.push(getPlayListDetail(id))
    }
    Promise.all(promises).then((res) => {
      const playLists = res.map((i) => {
        i.playlist
      })
      dispatch(changeRackingAction(playLists))
    })
  }
)

interface IRecommendState {
  banners: any[]
  recommend: any[]
  newAlbum: any[]
  ranking: any[]
}

const initialState: IRecommendState = {
  banners: [],
  recommend: [],
  newAlbum: [],
  ranking: []
}

const recommends = createSlice({
  name: 'recommend',
  initialState,
  reducers: {
    changeBannerAction(state, { payload }) {
      state.banners = payload
    },
    changeHotRecommendAction(state, { payload }) {
      state.recommend = payload
    },
    changeNewAlbumActions(state, { payload }) {
      state.newAlbum = payload
    },
    changeRackingAction(state, { payload }) {
      state.ranking = payload
    }
  }
})
export const {
  changeBannerAction,
  changeHotRecommendAction,
  changeNewAlbumActions,
  changeRackingAction
} = recommends.actions
export default recommends.reducer
